package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizerFilter implements GlobalFilter, Ordered {

    private static final String TOKEN = "Token";
    private static final String LOGIN_PATH = "/api/v1/login/login_auth";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求头
        ServerHttpRequest request = exchange.getRequest();
        //响应头
        ServerHttpResponse response = exchange.getResponse();
        //todo 如果是登录请求直接放行
        if (request.getPath().toString().contains(LOGIN_PATH)) {
            return chain.filter(exchange);
        }

        //todo 1.拿到header
        HttpHeaders headers = request.getHeaders();
        //todo 2.拿到token
        String token = headers.getFirst(TOKEN);

        //todo 3.判断token是否为空以及是否合法
        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)){
            //token错误返回响应码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //没问题就放行
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
